package com.xmu.prcs.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.xmu.prcs.dao.PlantDao;
import com.xmu.prcs.entity.Plant;

/**
 * 
 * @author frequent
 * @version 1.0,2012-3-20
 *
 */
public class PlantDaoImpl extends GenericDaoImpl<Plant> implements PlantDao{

	public PlantDaoImpl() {
		super(Plant.class);
	}

	public List<Plant> findByPropety(String propety, Object param) {
		List<Plant> list = null;
		try{
//			list =this.find(query, param);
			String sql = "from Plant as model where model." + propety + " = ?";
			list = this.getHibernateTemplate().find(sql, param);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}catch(Throwable t){
			t.printStackTrace();
			return null;
		}
		return list;
	}

	public int countPlant( int idSubject, int idKindShu, String plantName) {
		//通过sql查询得到集合数
		String sql = "select count(1) from plant p";
		boolean emptyName = true;
		if(plantName != null && !plantName.equals("")){
			emptyName = false;
			sql += " where p.plantname like '%" + plantName + "%'";
		}
		if(idSubject != 0){
			if(emptyName){
				sql += " where";
			}else{
				sql += " and";
			}
			sql += " p.idsubject='" + idSubject + "'";
		}else if(idKindShu != 0){
			if(emptyName){
				sql += " where";
			}else{
				sql += " and";
			}
			sql += " p.idkindshu='" + idKindShu + "'";
		}
		
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createSQLQuery(sql);
		int size;
		if(query.uniqueResult() == null){
			size = 0;
		}
		size = Integer.parseInt((query.uniqueResult().toString()));
		return size;
	}

	public List<Plant> find4Page(int begin, int size, int idSubject, int idKindShu, String plantName) {
		String sql = "select * from plant";
		boolean emptyName = true;
		if(plantName != null && !plantName.equals("")){
			emptyName = false;
			sql += " where plant.plantname like '%" + plantName + "%'";
		}
		if(idSubject != 0){
			if(emptyName){
				sql += " where";
			}else{
				sql += " and";
			}
			sql += " plant.idsubject='" + idSubject + "'";
		}else if(idKindShu != 0){
			if(emptyName){
				sql += " where";
			}else{
				sql += " and";
			}
			sql += " plant.idkindshu='" + idKindShu + "'";
		}
		sql += " order by plant.uploadtime desc";
		Query query = getHibernateTemplate().getSessionFactory()
			.getCurrentSession().createSQLQuery(sql).addEntity(Plant.class);
		query.setFirstResult(begin);
		query.setMaxResults(size);
		
		return query.list();
	}

}
